import java.io.IOException;
import java.util.LinkedList;

/**
 * Authors - Oren Bracha, Rony Lahav & Yehuda Eterman
 * This class represents the updatedata command. It gets a Linked List containing the 
 * parameters for update and their values and performs the update in the DB (data validity checks are not performed!!)
 */
public class CmdUpdateData implements ICmd{
	
	private LinkedList<String[]> updatedData;	//list of command classes to execute
	private String command;                     //Command as it appeared in the input file
	
	// CTOR
	CmdUpdateData(LinkedList<String[]> updatedData, String command){
		this.updatedData=updatedData;
		this.command=command;
	}

	//reads the parameters to update and changes each one in the peer's tuple
	public void executeCmd(){
		Logger.getInstance().printCommandDetails("updatedata", command);
		DBTuple myTuple = proj350.getMyTuple();
		boolean done=false;
		boolean updatedPic=false; 
		for (String[] data : updatedData) {
			done=false;
			// IP update section
			if (!done && data[0].equals("ip")){
				myTuple.setIp(data[1]);
				done=true;
			}
			// tcp port update section
			if (!done && data[0].equals("tcp")){
				myTuple.setTcpPort(data[1]);
				done=true;
			}
			// udp port update section
			if (!done && data[0].equals("udp")){
				myTuple.setUdpPort(data[1]);
				done=true;
			}
			// phone update section
			if (!done && data[0].equals("phone")){
				myTuple.setPhoneNum(data[1]);
				done=true;
			}
			// email update section
			if (!done && data[0].equals("email")){
				myTuple.setEmailAddress(data[1]);
				done=true;
			}
			// picture update section
			if (!done && data[0].equals("pic")){
				boolean error = false;
				try {
					// Getting the new picture size
					myTuple.setPicSize(PictureHandler.getImageSize(data[1]));
				} catch (IOException e) {
					updatedPic=false;
					error = true;
				}
				if (!error){
					myTuple.setPictureFile(data[1]);
					done=true;
					updatedPic=true;
				}
			}
			// N parameter update section
			if (!done && data[0].equals("n")){
				proj350.setNParameter(Integer.parseInt(data[1]));
				done=true;
			}
		}
		// If everything was valid update the data in the DB
		if (done){
			String version = DateStringConverter.timeCurrentForMessages();
			if (updatedPic){
				myTuple.setPicVersion(version);
			}
			myTuple.setDbVersion(version);
			myTuple.setPeerVersion(version);
			myTuple.setPeerCommitTime(version);
		}
	}

}
